package CelestialDataAccess;

import java.security.Security;

import javax.crypto.spec.SecretKeySpec;
import javax.crypto.Cipher;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.InvalidKeyException;

class CryptService {

    private static String algorithm = "DESede";
    private static Key key = null;
    private static Cipher cipher = null;

    /*************************************************************************/
    /* helpers */
    private static void setUp() throws Exception {
        key = new SecretKeySpec(new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
    0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 }, "DESede");

        cipher = Cipher.getInstance(algorithm);
    }

    /*************************************************************************/
    /* client methods */
    static byte[] encrypt(String input) throws InvalidKeyException,
    BadPaddingException, IllegalBlockSizeException, Exception {

        setUp();

        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] inputBytes = input.getBytes();
        return cipher.doFinal(inputBytes);
    }
    /*----------------------------------------------------------------------*/
    static String decrypt(byte[] encryptionBytes) throws InvalidKeyException,
    BadPaddingException, IllegalBlockSizeException, Exception {
        
        setUp();
        
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] recoveredBytes =
          cipher.doFinal(encryptionBytes);
        String recovered =
          new String(recoveredBytes);
        return recovered;
    }
    /*************************************************************************/
    /* test */
    public static void main(String[] args) throws Exception {
        setUp();

        byte[] encryptionBytes = null;
        String input = "azsxdcfv";
        System.out.println("Entered: " + input);
        encryptionBytes = encrypt(input);
        System.out.println(encryptionBytes.length);
        for(int i=0; i< encryptionBytes.length;i++)
            System.out.printf("%x" + " ", encryptionBytes[i]);
        System.out.println(
          "\nRecovered: " + decrypt(encryptionBytes));
    }
}
